/*****************************************************************************
 * Product: 数据同步解决方案                                                    
 * Copyright (C) 2010-2011  瑞科软件. All Rights Reserved.                                                                       *
 * 改程序是开源的，您可以修改源代码，做二次开发，定制您自己的同步程序                     
 * 您可以通过我们的网站了解详细信息，包括安装与使用指南，  http://www.ruike.org         
 * 																		      			
 *****************************************************************************/
package com.mk;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLTree {
	public final static String insert = "insert";
	public final static String into = "into";
	public final static String left_square = "(";
	public final static String right_square = ")";
	public final static String dot = ",";
	public final static String word = "word";

	private String sql;
	public List<Token> words = new ArrayList<Token>();
	private int currentIndex = 0;

	public SQLTree(String sql) {
		super();
		this.sql = sql;
	}

	/**
	 * SQL解析的临时解决方案 Jul 26, 2009
	 */
	public static Map tempInsertMethod(String[] fields) {
		Map<String, String> aMap = new HashMap<String, String>();
		List<String> aList = new ArrayList<String>();
		List<String> aList2 = new ArrayList<String>();
		int i = 0;
		for (i = 0; i < fields.length; i++) {
			if (fields[i].equals("(")) {
				break;
			}
		}

		int j = 0;
		for (j = i + 1; j < fields.length; j++) {
			if (fields[j].equals(")")) {
				break;
			}
			if (j == 76) {
				int x = 9;
				x++;
			}
			if ((j - i) % 2 == 1) {
				aList.add(fields[j]);
			}
		}
		int z = 1;
		for (int k = j + 3; k < fields.length; k++) {
			if (z == 65) {
				int hh = 0;
				hh++;
			}
			if (fields[k].equals(")")) {
				break;
			}
			if (fields[k].equals(",")) {
				z++;
				continue;
			}
			if (fields[k].equals("TO_DATE")) {
				k += 5;

				aList2.add("2002-07-11 18:36:38");
				z++;
				continue;
			}

			if ((z) % 2 == 1) {
				z++;
				aList2.add(fields[k]);
			}
		}

		for (int m = 0; m < aList.size(); m++) {
			aMap.put(aList.get(m).toUpperCase(), aList2.get(m));
		}

		return aMap;
	}

	// // insert into T(A1,A2,A3)values('select name fron User','jsona',3)
	// public static void main(String args[]) {
	// String sql = "insert into
	// C_OrderLine(AD_Client_ID,AD_Org_ID,C_BPartner_Location_ID,C_UOM_ID,C_BPartner_ID,M_Product_ID,DateOrdered,DatePromised,Discount,FreightAmt,IsActive,IsDescription,Line,LineNetAmt,M_AttributeSetInstance_ID,M_Warehouse_ID,PriceActual,PriceCost,PriceEntered,PriceLimit,PriceList,Processed,QtyDelivered,QtyEntered,QtyInvoiced,QtyLostSales,QtyOrdered,QtyReserved,RRAmt,Updated,UpdatedBy,C_Currency_ID,C_Order_ID,C_OrderLine_ID,C_Tax_ID,Created,CreatedBy)
	// values
	// (1000000,1000002,1000009,100,1000010,1000466,TO_DATE('2010-07-16','YYYY-MM-DD'),TO_DATE('2010-07-16','YYYY-MM-DD'),0.00,0,'Y','N',10,30.00,0,1000002,30.00,0,30.00,13.00,30.00,'N',0,1,0,0,1,0,0,TO_DATE('2010-07-16
	// 21:22:30','YYYY-MM-DD
	// HH24:MI:SS'),1000003,332,201008016,201014023,1000000,TO_DATE('2010-07-16
	// 21:22:30','YYYY-MM-DD HH24:MI:SS'),1000003)";
	// SQLTree aSQLTree = new SQLTree(sql);
	// String[] as = aSQLTree.parse();
	// Map aMap = tempInsertMethod(as);
	// int i = as.length;
	// }

	public static Map getMap(String sql) {
		// String sql = "insert into
		// C_OrderLine(AD_Client_ID,AD_Org_ID,C_BPartner_Location_ID,C_UOM_ID,C_BPartner_ID,M_Product_ID,DateOrdered,DatePromised,Discount,FreightAmt,IsActive,IsDescription,Line,LineNetAmt,M_AttributeSetInstance_ID,M_Warehouse_ID,PriceActual,PriceCost,PriceEntered,PriceLimit,PriceList,Processed,QtyDelivered,QtyEntered,QtyInvoiced,QtyLostSales,QtyOrdered,QtyReserved,RRAmt,Updated,UpdatedBy,C_Currency_ID,C_Order_ID,C_OrderLine_ID,C_Tax_ID,Created,CreatedBy)
		// values
		// (1000000,1000002,1000009,100,1000010,1000466,TO_DATE('2010-07-16','YYYY-MM-DD'),TO_DATE('2010-07-16','YYYY-MM-DD'),0.00,0,'Y','N',10,30.00,0,1000002,30.00,0,30.00,13.00,30.00,'N',0,1,0,0,1,0,0,TO_DATE('2010-07-16
		// 21:22:30','YYYY-MM-DD
		// HH24:MI:SS'),1000003,332,201008016,201014023,1000000,TO_DATE('2010-07-16
		// 21:22:30','YYYY-MM-DD HH24:MI:SS'),1000003)";
		SQLTree aSQLTree = new SQLTree(sql);
		String[] as = aSQLTree.parse();
		Map aMap = tempInsertMethod(as);
		return aMap;
	}

	public String[] parse() {
		try {
			while (!this.readWorld()) {
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		String[] result = new String[words.size()];
		int i = 0;
		for (Token token : words) {
			result[i++] = token.getWord();
		}
		return result;
	}

	private void addToken(String word) {
		Token aToken = new Token();
		aToken.setWord(word);
		// if(word.equals(SQLTree.insert)) {
		// aToken.setType(SQLTree.insert);
		// }else if(word.equals(SQLTree.left_square)) {
		// aToken.setType(SQLTree.left_square);
		// }else if(word.equals(SQLTree.right_square)) {
		// aToken.setType(SQLTree.right_square);
		// }else if(word.equals(SQLTree.dot)) {
		// aToken.setType(SQLTree.dot);
		// }else if(word.equals(SQLTree.into)) {
		// aToken.setType(SQLTree.into);
		// }else {
		// aToken.setType(SQLTree.word);
		// }

		aToken.setType(SQLTree.word);
		words.add(aToken);
	}

	private boolean readWorld() throws ParseException {
		boolean isEOF = false;
		if (currentIndex == sql.length()) {
			isEOF = true;
			return isEOF;
		}
		char letter = sql.charAt(currentIndex);
		// 字符串，读取整个
		if (letter == '\'') {
			int subOffset = 1;
			char aChar = sql.charAt(currentIndex + subOffset);
			while (aChar != '\'' && currentIndex + subOffset <= sql.length()) {
				subOffset++;
				aChar = sql.charAt(currentIndex + subOffset);

			}
			if (aChar == '\'') {
				String aWord = sql.substring(currentIndex + 1, currentIndex
						+ subOffset);
				addToken(aWord);
			} else {
				throw new ParseException();
			}
			currentIndex += (subOffset + 1);

		} else if (letter == '(' || letter == ')' || letter == ','
				|| letter == '[' || letter == ']') {
			String aWord = new String(new char[] { letter });
			addToken(aWord);
			currentIndex++;
		} else if (letter == ' ') {
			currentIndex++;
			readWorld();
		} else {
			int subOffset = 1;
			char aChar = sql.charAt(currentIndex + subOffset);
			// 结尾
			while (aChar != ' ' && aChar != '(' && aChar != ')' && aChar != ','
					&& aChar != '[' && aChar != ']') {
				if (currentIndex + subOffset + 1 >= sql.length()) {
					String aWord = sql.substring(currentIndex, currentIndex
							+ subOffset + 1);
					addToken(aWord);
					currentIndex += subOffset;
					return true;
				}
				subOffset++;
				aChar = sql.charAt(currentIndex + subOffset);

			}
			String aWord = sql
					.substring(currentIndex, currentIndex + subOffset);
			addToken(aWord);
			currentIndex += subOffset;
		}
		return isEOF;

	}
}
